package wqh.controller.file;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import wqh.domain.Device;
import wqh.domain.GeoBuilding;
import wqh.domain.Monitor;
import wqh.domain.Sensor;
import wqh.global.GlobalSession;
import wqh.pojo.IPConver;
import wqh.pojo.MapRet;
import wqh.pojo.MonitorXls;
import wqh.pojo.xkLog;
import wqh.service.*;
import wqh.utils.XlsUtil;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by devts on 2016/11/12.
 */
@RestController
@CrossOrigin(origins = "*")
@RequestMapping("/import/monitor")
public class MonitorImport {

    @Autowired
    private GeoBuildingService geoBuildingService;

    @Autowired
    private DeviceService deviceService;

    @Autowired
    private SensorService sensorService;

    @Autowired
    private MonitorService monitorService;

    @Autowired
    private SystemLogService systemLogService;

    @ResponseBody
    @RequestMapping(value = "/xlsImport",method = RequestMethod.POST)
    public Object monitorXlsUpload(HttpServletRequest request, @RequestParam("file")MultipartFile file)
    {
        String sessionID = request.getSession().getId();
        String userName = GlobalSession.getUserNameBySessionID(sessionID);
        if(userName == null) userName = "空用户";

        try {
            String localPath = "WEB-INF\\upload\\xls\\";
            String uploadPath = request.getServletContext().getRealPath("/") + localPath;
            File uploadDir = new File(uploadPath);
            if(!uploadDir.exists())
            {
                uploadDir.mkdirs();
            }
            String fileName = file.getOriginalFilename();
            if(fileName == null)
            {
                return MapRet.FILE_UPLOAD_ERROR();
            }
            byte[] bytes = file.getBytes();
            fileName = System.currentTimeMillis() + fileName;
            File serverFile = new File(uploadDir.getAbsolutePath() + File.separator + fileName);
            BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(serverFile));
            stream.write(bytes);
            stream.close();
            XlsUtil xlsUtil = new XlsUtil();
            Map<String, Object> map = xlsUtil.readXlsFile(new FileInputStream(serverFile));
//            serverFile.delete();
            if(map.get("error") != null) return map.get("error");
            @SuppressWarnings("unchecked")
            List<MonitorXls> importList = (List<MonitorXls>) map.get("data");
            List<Object> errorRecord = new ArrayList<Object>();
            int successCount = 0;

            List<GeoBuilding> geoBuildingList = geoBuildingService.findAllRecord();
            List<Sensor> sensorList = sensorService.findAllRecord();

            for(int i = 0; i < importList.size(); i++)
            {
                MonitorXls monitorXls = importList.get(i);
                List<Device> deviceList = deviceService.findAllByNameAndIP(monitorXls.getDevice(), IPConver.Ip2Int(monitorXls.getDevice_ip()));
                //简单判断有效数据
                if(geoBuildingList == null || geoBuildingList.size() == 0)
                {
                    errorRecord.add("xls第" + (i+3) +"行地理位置信息");
                    continue;
                }
                if(deviceList == null || deviceList.size() == 0)
                {
                    errorRecord.add("xls第" + (i+3) +"行用户信息传输装置信息");
                    continue;
                }
                if(sensorList == null || sensorList.size() == 0)
                {
                    errorRecord.add("xls第" + (i+3) +"行传感器类别信息");
                }
                if(monitorXls.getDevice() == null || monitorXls.getDevice().length() == 0)
                {
                    errorRecord.add("错误行"+(i+2));
                    continue;
                }
                if(monitorXls.getDevice_ip() == null || monitorXls.getDevice_ip().length() == 0)
                {
                    errorRecord.add("错误行"+(i+2));
                    continue;
                }
                if(monitorXls.getArea() == null || monitorXls.getArea().length() == 0)
                {
                    errorRecord.add("错误行"+(i+2));
                    continue;
                }
                if(monitorXls.getBuilding() == null || monitorXls.getBuilding().length() == 0)
                {
                    errorRecord.add("错误行"+(i+2));
                    continue;
                }
                if(monitorXls.getFloor() == null || monitorXls.getFloor().length() == 0)
                {
                    errorRecord.add("错误行"+(i+2));
                    continue;
                }
                if(monitorXls.getSensor() == null || monitorXls.getSensor().length() == 0)
                {
                    errorRecord.add("错误行"+(i+2));
                    continue;
                }
                if(monitorXls.getMonitor() == null || monitorXls.getMonitor().length() == 0)
                {
                    errorRecord.add("错误行"+(i+2));
                    continue;
                }
                if(monitorXls.getAlarm() == null || monitorXls.getAlarm().length() == 0)
                {
                    errorRecord.add("错误行"+(i+2));
                    continue;
                }
                //判断数据库和xls数据有效结束

                //判断用户信息传输装置
                boolean row = false;
                if(monitorXls.getDevice_ip().equals(IPConver.int2Ip(deviceList.get(0).getIp())))
                {
                    Device currentDevice = deviceList.get(0);
                    //判断地理位置信息
                    for(GeoBuilding g1 : geoBuildingList)
                    {
                        if(g1.getName().equals(monitorXls.getArea()) && g1.getLevel() == 1)
                        {
                            for(GeoBuilding g2 : geoBuildingList)
                            {
                                if(g2.getName().equals(monitorXls.getBuilding()) && g2.getLevel() == 2 && g2.getParent_id().equals(g1.getId()))
                                {
                                    for(GeoBuilding g3 : geoBuildingList)
                                    {
                                        if(g3.getName().equals(monitorXls.getFloor()) && g3.getLevel() == 3 && g3.getParent_id().equals(g2.getId()))
                                        {
                                            if(sensorList != null)
                                            {
                                                //判断传感器类别
                                                for(Sensor s : sensorList)
                                                {

                                                    if(s.getName().equals(monitorXls.getSensor()))
                                                    {
                                                        //// TODO: 2016/10/6
                                                        //这里这是初步实现，以后还要判断监测点是否在数据库中已经存在。
                                                        Monitor monitor = new Monitor(g1.getId(),g2.getId(),g3.getId(),currentDevice.getId(),s.getId(),monitorXls.getMonitor(),monitorXls.getAlarm());
                                                        monitorService.insertRecord(monitor);
                                                        successCount++;
                                                        row = true;
                                                        break;
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                if(!row)
                {
                    errorRecord.add("请检查第" + (i+3) + "行数据中每一列数据输入的是否正确。");
                }
            }
            Map<String,Object> ret = new HashMap<String, Object>();
            ret.put("xls文件中的监测点数目" ,importList.size());
            ret.put("成功导入的监测点数目", successCount);
            ret.put("错误内容",errorRecord);
            if(errorRecord.size() == 0) xkLog.addLog(systemLogService,"导入 " + file.getOriginalFilename(),xkLog.getFileConfig(),userName);

            return MapRet.DATA(ret);
        }catch (Exception e)
        {
            e.printStackTrace();
            return MapRet.FILE_UPLOAD_ERROR();
        }
    }

}
